Skip to content

Instantly share code, notes, and snippets.

@jfensign
Created April 9, 2012 00:24
Show Gist options
  • Save jfensign/2340496 to your computer and use it in GitHub Desktop.
Save jfensign/2340496 to your computer and use it in GitHub Desktop.
NodeJS User Registration and Authentication
//index.js
var express = require('express'),
app = module.exports = express.createServer(),
mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/nodeAuth');
//configure app
app.configure(function() {
app.set('views', __dirname + '/views');
app.set('view_options', {layout : false});
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use("/assets", express.static(__dirname + '/assets'));
app.use('/models', __dirname + '/models');
});
//include the maps controller
var users = require('./controllers/users_controller.js');
//app.<REQUEST_METHOD>(<REQUEST_URI>, <CONTROLLER_METHOD>)
app.get('/users/create', users.create);
app.post('/users/create', users.create);
app.get('/users/login', users.login);
app.post('/users/login', users.login);
app.listen(3385);
//login.jade
!!! 5
html
head
title Login
body
h1 Login
form(name = "login", action = "/users/login", method = "post")
| Email
input(type="text", name="email", id="email")
br
| Password
input(type="text", name="password", id="password")
br
input(type="submit", value="Login")
//signup.jade
!!! 5
html
head
title Sign Up
body
h1 Sign Up
form(name = "find", action = "/users/create", method = "post")
| Firstname
input(type="text", name="firstname", id="firstname")
br
| Lastname
input(type="text", name="lastname", id="lastname")
br
| Email
input(type="text", name="email", id="email")
br
| Password
input(type="password", name="password", id="password")
br
| Repeat Password
input(type="password", name="repeat_password", id="repeat_password")
br
input(type="submit", value="Search")
//users_controller.js
var crypto = require("crypto");
var user = require("../models/users_model.js");
var UserModel = new user();
exports.create = function(req, res) {
if(req.method.toLowerCase() != "post") {
res.render("signup.jade", {layout: false});
}
else {
new user(req.body).save();
res.send("ok");
}
}
exports.login = function(req, res) {
if(req.method.toLowerCase() != "post") {
res.render("login.jade", {layout: false});
}
else {
user.findOne({email: req.body.email}, function(err, result) {
if(err) console.log(err);
if(result == null) {
res.send('invalid username',
{'Content-type' : 'text/plain'},
403);
}
else {
auth(result);
}
});
function auth( userRes ) {
if(!UserModel.encrypt(req.body.password) == userRes.password) {
res.send('invalid password',
{'Content-type' : 'text/plain'},
403);
} else {
console.log(userRes._id);
user.update({_id : userRes._id}, {'$set' : {token : Date.now}});
res.send(userRes);
}
}
}
}
//user_model.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
ObjectId = Schema.ObjectId,
crypto = require('crypto'),
require('assert');
var algorithm = 'aes256';
var key = 'D#$DF#QD#@~!W@E@';
var pw = '';
//USER SCHEMA
var userSchema = new Schema({
ObjectId: ObjectId,
date: {type: Date, default: Date.now},
firstname: {type: String},
lastname: {type: String},
email: {type: String, unique: true},
password: String
});
//encrypt method
userSchema.methods.encrypt = function encrypt(str) {
pw = str;
var cipher = crypto.createCipher(algorithm, key);
var encrypted = cipher.update(pw, 'utf8', 'hex') + cipher.final('hex');
console.log("ENCRYPTED: " + encrypted);
return encrypted;
}
//password setter
userSchema.path('password').set(function(v) {
return this.encrypt(v);
});
module.exports = mongoose.model('User', userSchema);
@CharlesDCB
Copy link

Bonjour existe-t-il un petit tuto pour mettre en place tout ça?

@Steves1996
Copy link

j'ai implementer un code semblabe mais j'ai une erreur qui persiste toujours celle-ci:
Cannot read property 'lastName' of undefined. cela c'est quand je mais les attributs de ma collection et quand je fait comme ceci ''var user= new User (req.body)'' sa enregistre sans mettre les donnees de user dans la bd. pardon besoin d'aide merci

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment