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