From 06ea48caa58680bf0ab48ffadfa70b31fc615c0e Mon Sep 17 00:00:00 2001 From: Dennis Eriksen Date: Wed, 24 Apr 2013 23:00:34 +0200 Subject: set port to 3000 --- app.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app.js b/app.js index 7fd9cbb..9fcfc31 100644 --- a/app.js +++ b/app.js @@ -17,7 +17,7 @@ var app = express(); // initiates express app.configure(function(){ // this controls the port the application will be running on. // by adding 'process.enc.PORT' we enable the app to run on automated systems like heroku - app.set('port', process.env.PORT || 8000); + app.set('port', process.env.PORT || 3000); app.set('views', __dirname + '/views'); // sets views to the right directory app.set('view engine', 'ejs'); // initiates viewengine. We use EJS, or embedded js - http://embeddedjs.com/ -- cgit v1.2.3 From b749f84e93e9ef8b46446bca785222351ca579f4 Mon Sep 17 00:00:00 2001 From: Dennis Eriksen Date: Wed, 24 Apr 2013 23:29:01 +0200 Subject: cleaned up package.json --- package.json | 49 +++++++++++++++++++++++++++++-------------------- 1 file changed, 29 insertions(+), 20 deletions(-) diff --git a/package.json b/package.json index e218182..48ae466 100644 --- a/package.json +++ b/package.json @@ -1,22 +1,31 @@ { - "name": "DERS", - "version": "0.0.1", - "private": true, - "scripts": { - "start": "nodemon app" - }, - "dependencies": { - "express": "3.1.0", - "ejs": "*", - "mongoose": "*", - "connect": "*", - "emailjs": "*", - "mongodb": "*", - "moment": "*", - "less-middleware": "*", - "passport": "*", - "passport-local": "*", - "passport-facebook": "*", - "bcrypt": "*" - } + "name": "Divid" + , "description": "A bachelorproject ending in a webapplication for social accounting" + , "version": "0.0.2" + , "private": true + , "engines": { + "node": "0.10.x" + , "npm": "1.2.x" + } + , "scripts": { + "start": "NODE_ENV=development ./node_modules/.bin/nodemon app.js" + , "test": "NODE_ENV=test ./node_modules/.bin/mocha --reporter spec test/test-*.js" + } + , "dependencies": { + "express": "latest" + , "ejs": "latest" + , "mongoose": "latest" + , "connect": "latest" + , "mongodb": "latest" + , "less-middleware": "latest" + , "passport": "latest" + , "passport-local": "latest" + , "passport-facebook": "latest" + , "passport-twitter": "latest" + , "bcrypt": "latest" + , "nodemon": "latest" + } + , "decDependencies": { + "mocha": "latest" + } } -- cgit v1.2.3 From edd995fd5f92bba8221c7b9384ad0cb7c59794e3 Mon Sep 17 00:00:00 2001 From: Dennis Eriksen Date: Thu, 25 Apr 2013 01:21:07 +0200 Subject: moved express config to own file. created configfile. --- app.js | 39 ++++++++++++------------------------ config/config.js | 15 ++++++++++++++ config/express.js | 60 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ package.json | 2 +- 4 files changed, 89 insertions(+), 27 deletions(-) create mode 100644 config/config.js create mode 100644 config/express.js diff --git a/app.js b/app.js index 9fcfc31..c292af9 100644 --- a/app.js +++ b/app.js @@ -5,45 +5,32 @@ var express = require('express') , path = require('path') - , bcrypt = require('bcrypt') , passport = require('passport'); + var app = express(); // initiates express /** * App configuration */ +var port = process.env.PORT || 3000 + , env = process.env.NODE_ENV || 'development' + , config = require('./config/config')[env]; -app.configure(function(){ - // this controls the port the application will be running on. - // by adding 'process.enc.PORT' we enable the app to run on automated systems like heroku - app.set('port', process.env.PORT || 3000); - - app.set('views', __dirname + '/views'); // sets views to the right directory - app.set('view engine', 'ejs'); // initiates viewengine. We use EJS, or embedded js - http://embeddedjs.com/ - app.use(express.favicon(__dirname + '/public/faviconb.ico')); // sets favicon - app.use(express.logger('dev')); - app.use(express.bodyParser()); - app.use(express.cookieParser()); - app.use(express.session({ secret: 'lsdrghoi4hgqio42nqf2uqi32f3bilu23fl23b' })); - app.use(express.methodOverride()); - app.use(require('less-middleware')({ src: __dirname + '/public' })); - app.use(express.static(path.join(__dirname, 'public'))); - app.use(passport.initialize()); - app.use(passport.session()); -}); -app.configure('development', function(){ - app.use(express.errorHandler()); -}); +/** + * Express + */ +var app = express(); +// express settings +require('./config/express')(app, config, passport); /** * Routes */ - -require('./router')(app); +require('./router')(app, config); @@ -51,8 +38,8 @@ require('./router')(app); * Server initiation */ -app.listen(app.get('port'), function() { - console.log("Express server listening on port " + app.get('port')); +app.listen(port, function() { + console.log("Express server listening on port " + port); }); diff --git a/config/config.js b/config/config.js new file mode 100644 index 0000000..8312ddc --- /dev/null +++ b/config/config.js @@ -0,0 +1,15 @@ +var path = require('path') + , rootPath = path.normalize(__dirname + '/..'); + + +module.exports = { + development: { + db: 'mongodb://localhost/test', + root: rootPath, + app: { + name: 'Divid' + } + } +} + + diff --git a/config/express.js b/config/express.js new file mode 100644 index 0000000..4afd827 --- /dev/null +++ b/config/express.js @@ -0,0 +1,60 @@ + +/** + * Module dependencies + */ + +var express = require('express'); + + +/** + * Module + */ + +module.exports = function (app, config, passport) { + + //sets view engine and path + app.set('views', config.root + '/views'); + app.set('view engine', 'ejs'); + + app.use(express.static(config.root + '/public')); + + // don't use logger for test enc + if (process.env.NODE_ENV !== 'test') app.use(express.logger('dev')); + + + app.configure(function () { + + app.use(express.cookieParser()); //must be above sessions + + app.use(express.bodyParser()); //must be above methodOverride + + app.use(express.methodOverride()); + + app.use(express.session({ secret: 'lsdrghoi4hgqio42nqf2uqi32f3bilu23fl23b' })); + + // use passport session + app.use(passport.initialize()); + app.use(passport.session()); + + app.use(express.favicon(__dirname + '/public/faviconb.ico')); + + // use LESS for CSS + app.use(require('less-middleware')({ src: config.root + '/public' })); + + app.use(app.router); + + app.use(function(err, req, res, next) { + if (~err.message.indexOf('not fount')) return next(); // treat like 404 + + console.error(err.stack); + + res.status(500).render('500', { error: err.stack }); // render page + }); + + app.use(function(req, res, next) { + res.status(404).render('404', { url: req.originalUrl, error: 'Not found' }); // render page + }); + }); +} + + diff --git a/package.json b/package.json index 48ae466..08595cb 100644 --- a/package.json +++ b/package.json @@ -25,7 +25,7 @@ , "bcrypt": "latest" , "nodemon": "latest" } - , "decDependencies": { + , "devDependencies": { "mocha": "latest" } } -- cgit v1.2.3 From 9b5bf91eab12d6c1a5f88180288653f7056285f3 Mon Sep 17 00:00:00 2001 From: Dennis Eriksen Date: Thu, 25 Apr 2013 01:24:22 +0200 Subject: test commit to dev branch --- app.js | 1 - 1 file changed, 1 deletion(-) diff --git a/app.js b/app.js index c292af9..67a1b13 100644 --- a/app.js +++ b/app.js @@ -33,7 +33,6 @@ require('./config/express')(app, config, passport); require('./router')(app, config); - /** * Server initiation */ -- cgit v1.2.3 From 4dd7550b87386114ba4e86be17afbaa4d3fa11d6 Mon Sep 17 00:00:00 2001 From: Dennis Eriksen Date: Thu, 25 Apr 2013 02:12:34 +0200 Subject: addedpassport config file and did some other stuff --- config/config.js | 5 +++ config/passport.js | 109 +++++++++++++++++++++++++++++++++++++++++++++++++++++ router.js | 8 ++-- 3 files changed, 117 insertions(+), 5 deletions(-) create mode 100644 config/passport.js diff --git a/config/config.js b/config/config.js index 8312ddc..1eaffa1 100644 --- a/config/config.js +++ b/config/config.js @@ -8,6 +8,11 @@ module.exports = { root: rootPath, app: { name: 'Divid' + }, + facebook: { + clientID: "504825706245603", + clientSecret: "e5ea0faed85d8749cafd38732530ef35", + callbackURL: "https://divid.no/auth/facebook/callback" } } } diff --git a/config/passport.js b/config/passport.js new file mode 100644 index 0000000..9518409 --- /dev/null +++ b/config/passport.js @@ -0,0 +1,109 @@ +// dependencies +var mongoose = require('mongoose') + , LocalStrategy = require('passport-local').Strategy + , FacebookStrategy = require('passport-facebook').Strategy + , TwitterStrategy = require('passport-twitter').Strategy + , User = mongoose.model('User'); + +/** + * This is where the magic happends + */ + +module.exports = function (passport, config) { + + // serialize sessions + passport.serializeUser( function(user, done) { + done(null, user.id); + }); + passport.deserializeUser( function(id, done) { + User.findOne({ _id: id }, function(err, user) { + done(err, user); + }); + }); + + + /** + * Local strategy + */ + passport.use(new LocalStrategy({ + usernameField: 'email', + passwordField: 'password' + }, function(email, password, done) { + + // looks up the user in the database, and check if password matches + User.findOne({ email: email }, function(err, user) { + if (err) return done(err); + if (!user) return done(null, false, { message: 'Unknown user' }); + if (!user.authenticate(password)) return done(null, false, { message: 'Invalid password' }); + return done(null, user); + }); + })); + + + /** + * Facebook strategy + */ + passport.use(new FacebookStrategy({ + clientID: config.facebook.clientID + , clientSecret: config.facebook.clientSecret + , callbackURL: config.facebook.callbackURL + }, function(accessToken, refreshToken, profile, done) { + + // looks up the user in the database. Will create the user if it does not exist + User.findOne({ 'facebook.id': profile.id }, function(err, user) { + if(err) return done(err); + if (!user) { + user = new User({ + name: profile.displayName + , email: profile.emails[0].value + , username: profile.username + , provider: 'facebook' + , facebook: profile._json + }); + user.save(function(err) { + if (err) console.log(err); + return done(err, user); + }); + } else { + return done(err, user); + } + }); + })); + + + /** + * Twitter strategy + */ + passport.use(new TwitterStrategy({ + consumerKey: config.twitter.clientID + , consumerSecret: config.twitter.clientSecret + , callbackURL: config.twitter.callbackURL + }, function(token, tokenSecret, profile, done) { + + // looks up the user in the database. Will create the user if it does not exist + User.findOne({ 'twitter.id': profile.id }, function(err, user) { + if (err) return done(err); + if (!user) { + user = new User({ + name: profile.displayName + , username: profile.username + , provider: 'twitter' + , twitter: profile._json + }); + user.save(function(err) { + if (err) console.log(err); + return done(err, user); + }); + } else { + return done(err, user); + } + }); + })); + + + + + + +} + diff --git a/router.js b/router.js index cf3bd51..0750bdf 100644 --- a/router.js +++ b/router.js @@ -6,8 +6,6 @@ var passport = require('passport') , bcrypt = require('bcrypt') , SALT_WORK_FACTOR = 15; -var FACEBOOK_APP_ID = "504825706245603"; -var FACEBOOK_APP_SECRET = "e5ea0faed85d8749cafd38732530ef35"; // connects to mongodb mongoose.connect('localhost', 'test'); @@ -135,9 +133,9 @@ passport.use(new LocalStrategy(function(username, password, done) { // credentials (in this case, an accessToken, refreshToken, and Facebook // profile), and invoke a callback with a user object. passport.use(new FacebookStrategy({ - clientID: FACEBOOK_APP_ID, - clientSecret: FACEBOOK_APP_SECRET, - callbackURL: "https://divid.no/auth/facebook/callback" + clientID: config.facebook.clientID, + clientSecret: config.facebook.clientSecret, + callbackURL: config.facebook.callbackURL }, function(accessToken, refreshToken, profile, done) { // asynchronous verification, for effect... process.nextTick(function() { -- cgit v1.2.3 From a82fe16c44a6005546131e58c88c02474243105a Mon Sep 17 00:00:00 2001 From: Dennis Eriksen Date: Thu, 25 Apr 2013 02:21:53 +0200 Subject: added twitter config --- config/config.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/config/config.js b/config/config.js index 1eaffa1..f932387 100644 --- a/config/config.js +++ b/config/config.js @@ -14,6 +14,11 @@ module.exports = { clientSecret: "e5ea0faed85d8749cafd38732530ef35", callbackURL: "https://divid.no/auth/facebook/callback" } + twitter: { + clientID: "CONSUMER KEY", + clientSecret: "CONSUMER SECRET", + callbackURL: "https://divid.no/auth/twitter/callback" + } } } -- cgit v1.2.3 From ed340574509eef6de3587c7191bb3977335319ce Mon Sep 17 00:00:00 2001 From: Dennis Eriksen Date: Thu, 25 Apr 2013 08:43:26 +0200 Subject: branch test --- app.js | 1 - 1 file changed, 1 deletion(-) diff --git a/app.js b/app.js index 67a1b13..2c93264 100644 --- a/app.js +++ b/app.js @@ -42,4 +42,3 @@ app.listen(port, function() { }); - -- cgit v1.2.3 From d4b85e5e7765def9820dab5129f80d238e515591 Mon Sep 17 00:00:00 2001 From: Dennis Eriksen Date: Thu, 25 Apr 2013 16:34:48 +0200 Subject: fixed small bug --- config/config.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/config.js b/config/config.js index f932387..8d120b2 100644 --- a/config/config.js +++ b/config/config.js @@ -13,7 +13,7 @@ module.exports = { clientID: "504825706245603", clientSecret: "e5ea0faed85d8749cafd38732530ef35", callbackURL: "https://divid.no/auth/facebook/callback" - } + }, twitter: { clientID: "CONSUMER KEY", clientSecret: "CONSUMER SECRET", -- cgit v1.2.3 From a0dbc1b3b71acc340d1099b8711d411128ee17f7 Mon Sep 17 00:00:00 2001 From: Dennis Eriksen Date: Thu, 25 Apr 2013 17:00:26 +0200 Subject: removed some passport classes that's going in config/passport.js --- router.js | 42 ------------------------------------------ 1 file changed, 42 deletions(-) diff --git a/router.js b/router.js index 0750bdf..9b6744f 100644 --- a/router.js +++ b/router.js @@ -1,6 +1,4 @@ var passport = require('passport') - , LocalStrategy = require('passport-local').Strategy - , FacebookStrategy = require('passport-facebook').Strategy , mongodb = require('mongodb') , mongoose = require('mongoose') , bcrypt = require('bcrypt') @@ -108,46 +106,6 @@ passport.deserializeUser( function(token, done) { } else { done(null, token); } }); -// Use the LocalStrategy within Passport. -// Strategies in passport require a `verify` function, which accept -// credentials (in this case, a username and password), and invoke a callback -// with a user object. In the real world, this would query a database; -// however, in this example we are using a baked-in set of users. -passport.use(new LocalStrategy(function(username, password, done) { - User.findOne({ username: username }, function(err, user) { - if (err) return done(err); - if (!user) { return done(null, false, { message: 'Unknown user ' + username }); } - user.comparePassword(password, function(err, isMatch) { - if (err) return done(err); - if (isMatch) { - return done(null, user); - } else { - return done(null, false, { message: 'Invalid password' }); - } - }); - }); -})); - -// Use the FacebookStrategy within Passport. -// Strategies in Passport require a `verify` function, which accept -// credentials (in this case, an accessToken, refreshToken, and Facebook -// profile), and invoke a callback with a user object. -passport.use(new FacebookStrategy({ - clientID: config.facebook.clientID, - clientSecret: config.facebook.clientSecret, - callbackURL: config.facebook.callbackURL -}, function(accessToken, refreshToken, profile, done) { - // asynchronous verification, for effect... - process.nextTick(function() { - - // To keep the example simple, the user's Facebook profile is returned to - // represent the logged-in user. In a typical application, you would want - // to associate the Facebook account with a user record in your database, - // and return that user instead. - return done(null, profile); - }); - } -)); // to ensure that users are logged in function ensureAuthenticated(req, res, next) { -- cgit v1.2.3 From ff55ba7557f83a99a6e3cd0e26cf627b8890ed71 Mon Sep 17 00:00:00 2001 From: Dennis Eriksen Date: Fri, 26 Apr 2013 17:42:44 +0200 Subject: added twitter authentication --- config/config.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/config/config.js b/config/config.js index 8d120b2..50dea23 100644 --- a/config/config.js +++ b/config/config.js @@ -15,8 +15,8 @@ module.exports = { callbackURL: "https://divid.no/auth/facebook/callback" }, twitter: { - clientID: "CONSUMER KEY", - clientSecret: "CONSUMER SECRET", + clientID: "tpCfKBUyAfogTpFxnb9w", + clientSecret: "abzInK4Nu0IFUhyXl73O2XjlFLFlzmBtLmbXk6v8", callbackURL: "https://divid.no/auth/twitter/callback" } } -- cgit v1.2.3 From fc50b5b7f18d02ffa8056dc1edbd3bd43e973493 Mon Sep 17 00:00:00 2001 From: Dennis Eriksen Date: Mon, 29 Apr 2013 03:39:15 +0200 Subject: been cleaning a bit, moving stuff to where it belongs. signup and signin works. --- app.js | 22 +++- config/email-settings.js | 13 -- config/express.js | 4 +- config/middlewares/authorization.js | 13 ++ controllers/users.js | 62 +++++++++ models/user.js | 128 ++++++++++++++++++ router.js | 44 ++----- views/navbar.ejs | 4 +- views/signup.ejs | 251 +----------------------------------- 9 files changed, 242 insertions(+), 299 deletions(-) delete mode 100644 config/email-settings.js create mode 100644 config/middlewares/authorization.js create mode 100644 controllers/users.js create mode 100644 models/user.js diff --git a/app.js b/app.js index 86b2fb9..5bc039d 100644 --- a/app.js +++ b/app.js @@ -4,7 +4,7 @@ */ var express = require('express') - , path = require('path') + , fs = require('fs') , passport = require('passport'); @@ -13,10 +13,24 @@ var app = express(); // initiates express /** * App configuration */ -var port = process.env.PORT || 3000 +var port = process.env.PORT || 8000 , env = process.env.NODE_ENV || 'development' - , config = require('./config/config')[env]; + , config = require('./config/config')[env] + , auth = require('./config/middlewares/authorization') + , mongoose = require('mongoose'); +// Bootstrap db connection +mongoose.connect(config.db); + + +// Bootstrap models +var models_path = __dirname + '/models'; +fs.readdirSync(models_path).forEach( function(file) { + require(models_path + '/' + file); +}); + +// Bootstrap passport config +require('./config/passport')(passport, config); /** * Express @@ -29,7 +43,7 @@ require('./config/express')(app, config, passport); /** * Routes */ -require('./router')(app, config); +require('./router')(app, passport, auth); /** diff --git a/config/email-settings.js b/config/email-settings.js deleted file mode 100644 index 8bc9983..0000000 --- a/config/email-settings.js +++ /dev/null @@ -1,13 +0,0 @@ -/** - * Email settings - */ - -module.exports = { - - host: 'localhost', - user: 'divid', - password: '', - sender: 'Divid ' - -} - diff --git a/config/express.js b/config/express.js index 4afd827..eb10b20 100644 --- a/config/express.js +++ b/config/express.js @@ -48,11 +48,11 @@ module.exports = function (app, config, passport) { console.error(err.stack); - res.status(500).render('500', { error: err.stack }); // render page + res.status(500).render('error', { title: '500', text: 'En serverfeil oppstod', error: err.stack }); // render page }); app.use(function(req, res, next) { - res.status(404).render('404', { url: req.originalUrl, error: 'Not found' }); // render page + res.status(404).render('error', { title: '404', text: 'Fant ikke siden du så etter' }); // render page }); }); } diff --git a/config/middlewares/authorization.js b/config/middlewares/authorization.js new file mode 100644 index 0000000..440f085 --- /dev/null +++ b/config/middlewares/authorization.js @@ -0,0 +1,13 @@ + + +/* + * Generic require login routing + */ + +exports.requiresLogin = function(req, res, next) { + if (!req.isAuthenticated()) return res.redirect('/login'); + next(); +} + + + diff --git a/controllers/users.js b/controllers/users.js new file mode 100644 index 0000000..af454b5 --- /dev/null +++ b/controllers/users.js @@ -0,0 +1,62 @@ + +/** + * Module dependencies + */ + +var mongoose = require('mongoose') + , User = mongoose.model('User'); + +/** + * Login + */ + +exports.login = function(req, res) { + res.render('login', { + title: 'Login' + }); + +} + + +/** + * Logout + */ + +exports.logoug = function(req, res) { + req.logout(); + res.resirect('/test'); +} + + +/** + * Signin + */ + +exports.signin = function(req, res) {} + +/** + * Create users + */ + +exports.create = function(req, res) { + var user = new User(req.body); + user.provider = 'local'; + user.save(function(err) { + if (err) return res.render('/signup', { errors: err.errors, user: user }); + req.logIn(user, function(err) { + if (err) return next(err); + return res.redirect('/dashboard'); + }); + }); +} + + +/** + * AuthCallback + * This is what happends when a user has signed in using facebook/twitter + */ + +exports.authCallback = function(req, res, next) { + res.redirect('/dashboard'); +} + diff --git a/models/user.js b/models/user.js new file mode 100644 index 0000000..b61f7c9 --- /dev/null +++ b/models/user.js @@ -0,0 +1,128 @@ + +/** + * Module dependencies + */ + +var mongoose = require('mongoose') + , Schema = mongoose.Schema + , crypto =require('crypto') + , authTypes = ['facebook', 'twitter']; + + +/** + * User schema + */ + +var UserSchema = new Schema({ + name: String, + email: String, + username: String, + provider: String, + hashed_password: String, + salt: String, + facebook: {}, + twitter: {} +}); + +/** + * Virtuals + */ + +UserSchema + .virtual('password') + .set(function(password) { + this._password = password + this.salt = this.makeSalt() + this.hashed_password = this.encryptPassword(password) + }).get(function() { return this._password }); + +/** + * Validations + */ +var validatePrecenceOf = function (value) { + return value && value.length; +} + +// the four validations below only apply if you are signing up traditionally + +UserSchema.path('name').validate(function(name) { + // if you're authenticated by any of the oauth strategies (facebook, twitter), don't validate + if(authTypes.indexOf(this.provider) !== -1) return true; + return name.length; +}, 'Name cannot be blank'); + +UserSchema.path('email').validate(function(email) { + if(authTypes.indexOf(this.provider) !== -1) return true; + return email.length; +}, 'Email cannot be blank'); + +UserSchema.path('username').validate(function(username) { + if(authTypes.indexOf(this.provider) !== -1) return true; + return username.length; +}, 'Username cannot be blank'); + +UserSchema.path('hashed_password').validate(function(hashed_password) { + if(authTypes.indexOf(this.provider) !== -1) return true; + return hashed_password.length; +}, 'Password cannot be blank'); + +/** + * Pre-save hook + */ + +UserSchema.pre('save', function(next) { + if (!this.isNew) return next(); + + if(!validatePrecenceOf(this.password) + && authTypes.indexOf(this.provider) === -1) + next(new Error('Invalid password')); + else next(); +}); + + +/** + * Methods + */ + +UserSchema.methods = { + + /** + * Authenticate - check if passwords are the same + * + * @param {String} plainText + * @return {Bolean} + * @api public + */ + + authenticate: function(plainText) { + return this.encryptPassword(plainText) === this.hashed_password; + }, + + /** + * Make salt + * + * @return {String} + * @api public + */ + + makeSalt: function() { + return Math.round((new Date().valueOf() * Math.random())) + ''; + }, + + /** + * Encrypt password + * + * @param {String} password + * @return {String} + * @api public + */ + + encryptPassword: function(password) { + if (!password) return ''; + return crypto.createHmac('sha1', this.salt).update(password).digest('hex'); + } +} + +mongoose.model('User', UserSchema); + + diff --git a/router.js b/router.js index 9b6744f..afb64e5 100644 --- a/router.js +++ b/router.js @@ -1,18 +1,16 @@ -var passport = require('passport') - , mongodb = require('mongodb') - , mongoose = require('mongoose') - , bcrypt = require('bcrypt') - , SALT_WORK_FACTOR = 15; +var mongodb = require('mongodb') + , mongoose = require('mongoose'); +var users = require('./controllers/users'); // connects to mongodb -mongoose.connect('localhost', 'test'); +//mongoose.connect('localhost', 'test'); var db = mongoose.connection; db.on('error', console.error.bind(console, 'connection error:')); db.once('open', function callback(){ console.log('Connected to MongoDB'); }); - +/* // user scheme var userSchema = mongoose.Schema({ username: { type: String, required: true, unique: true }, @@ -76,6 +74,7 @@ usr.save(function(err) { // the user by ID when deserializing. // // Both serializer and deserializer edited for Remember Me functionality +/* passport.serializeUser( function(user, done) { var createAccessToken = function() { var token = user.generateRandomToken(); @@ -113,7 +112,7 @@ function ensureAuthenticated(req, res, next) { if (req.isAuthenticated()) return next(); res.redirect('/login'); } - +/* /* * ============================================================ * Routes @@ -122,7 +121,7 @@ function ensureAuthenticated(req, res, next) { -module.exports = function(app) { +module.exports = function(app, passport, auth) { /* * GET home page. * @@ -183,10 +182,11 @@ module.exports = function(app) { /* POST */ - app.post('/login', function(req, res, next) { + app.post('/login', users.signin);/* function(req, res, next) { passport.authenticate('local', function(err, user, info) { if (err) return next(err); if (!user) { + console.log('post/login'); console.log(info.message); req.session.messages = [info.message]; return res.redirect('/login'); @@ -196,7 +196,7 @@ module.exports = function(app) { return res.redirect('/dashboard'); }) })(req, res, next); - }); + });*/ // GET /auth/facebook // Use passport.authenticate() as route middleware to authenticate the @@ -217,9 +217,8 @@ module.exports = function(app) { console.log('/auth/facebook/callback --- ' + req.user.username); res.redirect('/dashboard'); }); - - - + app.get('/auth/twitter', passport.authenticate('twitter', { failureRedirect: '/login' }), users.signin); + app.get('/auth/twitter/callback', passport.authenticate('twitter', { failureRedirect: '/login' }), users.authCallback); /* * GET logout @@ -261,22 +260,7 @@ module.exports = function(app) { /* POST */ - app.post('/signup', function(req, res) { - AM.addNewAccount({ - name : req.param('name'), - email : req.param('email'), - user : req.param('user'), - pass : req.param('pass'), - country : req.param('country') - }, function(e) { - if (e) { - res.send(e, 400); - } else { - res.send('ok', 200); - } - }); - }); - + app.post('/signup', users.create); diff --git a/views/navbar.ejs b/views/navbar.ejs index aac3c2e..79cb55a 100644 --- a/views/navbar.ejs +++ b/views/navbar.ejs @@ -30,7 +30,9 @@
- f + + f + t
diff --git a/views/signup.ejs b/views/signup.ejs index b64845b..01a5831 100644 --- a/views/signup.ejs +++ b/views/signup.ejs @@ -22,265 +22,18 @@ -
- -
- -
-

- +
- +
-- cgit v1.2.3 From c1371f712789e97fac6351daee93a048b12db69b Mon Sep 17 00:00:00 2001 From: Dennis Eriksen Date: Mon, 29 Apr 2013 04:13:18 +0200 Subject: cleaned up router.js --- app.js | 6 +- controllers/system.js | 62 ++++++++++++++ controllers/users.js | 15 ++-- router.js | 218 +++----------------------------------------------- 4 files changed, 88 insertions(+), 213 deletions(-) create mode 100644 controllers/system.js diff --git a/app.js b/app.js index 5bc039d..3d7cef3 100644 --- a/app.js +++ b/app.js @@ -21,7 +21,11 @@ var port = process.env.PORT || 8000 // Bootstrap db connection mongoose.connect(config.db); - +var db = mongoose.connection; +db.on('error', console.error.bind(console, 'connection error:')); +db.once('open', function callback(){ + console.log('Connected to MongoDB'); +}); // Bootstrap models var models_path = __dirname + '/models'; diff --git a/controllers/system.js b/controllers/system.js new file mode 100644 index 0000000..e54fc1c --- /dev/null +++ b/controllers/system.js @@ -0,0 +1,62 @@ + +/** + * Module dependencies + */ + + + + + +/** + * Before the user log in + * =============================================================== +*/ + +exports.index = function(req, res) { + res.render('index', { title: 'DERS' }); + }; + + + +exports.test = function(req, res) { + res.render('test', { + title: 'test', + loggedin: false + }); + }; + + +exports.home = function(req, res) { + res.render('home', { + title: 'home', + loggedin: false + }); + }; + + + + + + + +/** + * After the user has logged in + * =============================================================== +*/ + + + +exports.dashboard = function(req, res) { + console.log('/dashboard - ' + req.user); + res.render('dashboard', { + title: 'kanin', + loggedin: true + }); + }; + + + +exports.project = function(req, res) { + res.render('project', { title: 'Harepus', loggedin: true }); +} + diff --git a/controllers/users.js b/controllers/users.js index af454b5..d465468 100644 --- a/controllers/users.js +++ b/controllers/users.js @@ -9,7 +9,6 @@ var mongoose = require('mongoose') /** * Login */ - exports.login = function(req, res) { res.render('login', { title: 'Login' @@ -21,8 +20,7 @@ exports.login = function(req, res) { /** * Logout */ - -exports.logoug = function(req, res) { +exports.logout = function(req, res) { req.logout(); res.resirect('/test'); } @@ -30,14 +28,21 @@ exports.logoug = function(req, res) { /** * Signin + * This is triggered when the user post to /login */ - exports.signin = function(req, res) {} + /** - * Create users + * Signup */ +exports.signup = function(req, res) { + res.render('signup', { title: 'Registrer deg' }); +} +/** + * Create users + */ exports.create = function(req, res) { var user = new User(req.body); user.provider = 'local'; diff --git a/router.js b/router.js index afb64e5..72acd85 100644 --- a/router.js +++ b/router.js @@ -1,118 +1,6 @@ -var mongodb = require('mongodb') - , mongoose = require('mongoose'); - -var users = require('./controllers/users'); - -// connects to mongodb -//mongoose.connect('localhost', 'test'); -var db = mongoose.connection; -db.on('error', console.error.bind(console, 'connection error:')); -db.once('open', function callback(){ - console.log('Connected to MongoDB'); -}); -/* -// user scheme -var userSchema = mongoose.Schema({ - username: { type: String, required: true, unique: true }, - email: { type: String, required: true, unique: true }, - password: { type: String, required: true }, //passwords doesn't need to be unique - accessToken:{ type: String } // used for Remember Me -}); - -// bcrypt middleware -userSchema.pre('save', function(next) { - var user = this; - - if (!user.isModified('password')) return next(); - - bcrypt.genSalt(SALT_WORK_FACTOR, function(err, salt) { - if(err) return next(err); - - bcrypt.hash(user.password, salt, function(err, hash) { - user.password = hash; - next(); - }); - }); -}); - -// password verification -userSchema.methods.comparePassword = function(candidatePassword, cb) { - bcrypt.compare(candidatePassword, this.password, function(err, isMatch) { - if (err) return cb(err); - cb(null, isMatch); - }); -}; - -// remember me implementation -userSchema.methods.generateRandomToken = function () { - var user = this, - chars = "_!abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890", - token = new Date().getTime() + '_'; - for (var x = 0; x < SALT_WORK_FACTOR; x++) { - var i = Math.floor(Math.random() * 94); - token += chars.charAt(i); - } - return token; -}; +var users = require('./controllers/users') + , system = require('./controllers/system'); -// seed a test user -var User = mongoose.model('User', userSchema); -/* -var usr = new User({ username: 'bob', email: 'bob@example.com', password: 'secret' }); -usr.save(function(err) { - if (err) { - console.log(err); - } else { - console.log('user: ' + usr.username + + 'saved.'); - } -})*/ - -// Passport session setup. -// To support persistent login sessions, Passport needs to be able to -// serialize users into and deserialize users out of the session. Typically, -// this will be as simple as storing the user ID when serializing, and finding -// the user by ID when deserializing. -// -// Both serializer and deserializer edited for Remember Me functionality -/* -passport.serializeUser( function(user, done) { - var createAccessToken = function() { - var token = user.generateRandomToken(); - User.findOne( { accessToken: token }, function (err, existingUser) { - if (err) return done(err); - if (existingUser) { - createAccessToken(); //run it again. has to be unique - } else { - user.set('accessToken', token); - user.save( function(err) { - if (err) return done(err); - return done(null, user.get('accessToken')); - }); - } - }); - } - console.log('serializing user'); - if (user._id) { createAccessToken(); } - else { done(null, user); } -}); - -passport.deserializeUser( function(token, done) { - console.log('deserializing ' + token.provider); - if (token.provider === undefined) { - User.findOne( { accessToken: token }, function(err, user) { - done(err, user); - }); - } else { done(null, token); } -}); - - -// to ensure that users are logged in -function ensureAuthenticated(req, res, next) { - console.log('checking to see if authenticated'); - if (req.isAuthenticated()) return next(); - res.redirect('/login'); -} -/* /* * ============================================================ * Routes @@ -122,82 +10,24 @@ function ensureAuthenticated(req, res, next) { module.exports = function(app, passport, auth) { - /* - * GET home page. - * - * '/' - */ + app.get('/', system.index); - app.get('/', function(req, res){ - res.render('index', { title: 'DERS' }); - }); + app.get('/test', system.test); - /* - * GET TEST PAGE - * - * '/test' - */ + app.get('/home', system.home); - app.get('/test', function(req, res) { - res.render('test', { - title: 'test', - loggedin: false - }); - }); - app.get('/home', function(req, res) { - res.render('home', { - title: 'home', - loggedin: false - }); - }); - /* - * GET dashboard - * - * '/dashboard' - */ + app.get('/dashboard', system.dashboard); - app.get('/dashboard', function(req, res) { - console.log('/dashboard - ' + req.user); - res.render('dashboard', { - title: 'kanin', - loggedin: true - }); - }); + app.get('/login', users.login); - /* - * GET login page - * - * '/login' - */ - - app.get('/login', function(req, res) { - res.render('login', { title: 'Logg inn' }); - }); + app.post('/login', users.signin); - /* POST */ - - app.post('/login', users.signin);/* function(req, res, next) { - passport.authenticate('local', function(err, user, info) { - if (err) return next(err); - if (!user) { - console.log('post/login'); - console.log(info.message); - req.session.messages = [info.message]; - return res.redirect('/login'); - } - req.logIn(user, function(err) { - if (err) return next(err); - return res.redirect('/dashboard'); - }) - })(req, res, next); - });*/ - // GET /auth/facebook // Use passport.authenticate() as route middleware to authenticate the // request. The first step in Facebook authentication will involve @@ -225,10 +55,7 @@ module.exports = function(app, passport, auth) { * * '/logout' */ - app.get('/logout', function(req, res) { - req.logout(); - res.redirect('/test'); - }); + app.get('/logout', users.logout); @@ -239,11 +66,7 @@ module.exports = function(app, passport, auth) { * '/project' */ - app.get('/project', function(req, res) { - res.render('project', { title: 'Harepus', loggedin: true }); - }) - - + app.get('/project', system.project); @@ -253,9 +76,7 @@ module.exports = function(app, passport, auth) { * '/signup' */ - app.get('/signup', function(req, res) { - res.render('signup', { title: 'Registrer deg' }); - }); + app.get('/signup', users.signup); /* POST */ @@ -263,21 +84,4 @@ module.exports = function(app, passport, auth) { app.post('/signup', users.create); - - - /* - * ERRORS - */ - - /* 404 */ - app.get('*', function(req, res) { - res.render('error', { title: '404', text: 'Fant ikke siden' }); - }); - - /* 403 on POST */ - app.post('*', function(req, res) { - res.render('error', { title: '403', text: 'Du har ikke tilgang til denne siden' }); - }); - - }; -- cgit v1.2.3 From df0037739c7b9d06923be618d048d1bf3114e90a Mon Sep 17 00:00:00 2001 From: Dennis Eriksen Date: Mon, 29 Apr 2013 05:18:34 +0300 Subject: Added description It now says how to start the app. --- README.md | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 0082347..dd222c7 100644 --- a/README.md +++ b/README.md @@ -2,9 +2,26 @@ DERS ==== Bachelorprosjekt -hei + +Requirements: +- Node 0.10.x +- MongoDB + + +To run, first clone the project. + ```git clone git@github.com:dennisse/Divid.git``` + +Then install module dependencies by running ```npm install``` from inside the repository. + +Start the application with ```npm start``` + -Credit where credit is due: -https://github.com/braitsch/node-login + + + + + +Credit where credit is due: +https://github.com/madhums/nodejs-express-mongoose-demo -- cgit v1.2.3 From fd67955345b4e4a8b0209023ae3595f52b1ae0f7 Mon Sep 17 00:00:00 2001 From: Dennis Eriksen Date: Mon, 29 Apr 2013 04:25:27 +0200 Subject: removed bcrypt. no longer is use. --- package.json | 1 - 1 file changed, 1 deletion(-) diff --git a/package.json b/package.json index 08595cb..c2ca75b 100644 --- a/package.json +++ b/package.json @@ -22,7 +22,6 @@ , "passport-local": "latest" , "passport-facebook": "latest" , "passport-twitter": "latest" - , "bcrypt": "latest" , "nodemon": "latest" } , "devDependencies": { -- cgit v1.2.3 From 3c4cbdb56ba0c4347069406b3fe014b1f7ca6f1f Mon Sep 17 00:00:00 2001 From: Dennis Eriksen Date: Mon, 29 Apr 2013 04:26:55 +0200 Subject: removed small bug where express is initiated twice. also cleaned a bit. --- app.js | 6 ------ 1 file changed, 6 deletions(-) diff --git a/app.js b/app.js index 3d7cef3..acbc3ff 100644 --- a/app.js +++ b/app.js @@ -2,14 +2,10 @@ /** * Module dependencies. */ - var express = require('express') , fs = require('fs') , passport = require('passport'); - -var app = express(); // initiates express - /** * App configuration */ @@ -53,9 +49,7 @@ require('./router')(app, passport, auth); /** * Server initiation */ - app.listen(port, function() { console.log("Express server listening on port " + port); }); - -- cgit v1.2.3 From 53c89fd5bb00ed6c8100facb2a0ddcc54b8b9bb7 Mon Sep 17 00:00:00 2001 From: Dennis Eriksen Date: Mon, 29 Apr 2013 04:27:33 +0200 Subject: cleaning --- router.js | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/router.js b/router.js index 72acd85..a9d9c90 100644 --- a/router.js +++ b/router.js @@ -1,14 +1,18 @@ + +/** + * Dependencies + */ + var users = require('./controllers/users') , system = require('./controllers/system'); + /* * ============================================================ * Routes * */ - - module.exports = function(app, passport, auth) { app.get('/', system.index); -- cgit v1.2.3