Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

First commit

  • Loading branch information...
commit 8002d8623c38bceb14e3ab0c6ab3738172b928b3 0 parents
@tdksk authored
25 README.md
@@ -0,0 +1,25 @@
+mongoose-hashed-password
+========================
+
+hashed password setter to mongoose schema
+
+Ezample
+-------
+
+ require('mongoose-hashed-password');
+ var mongoose = require('mongoose');
+
+ var User = new mongoose.Schema({
+ user_id: String
+ });
+
+ User.setHashedPassword('sha256');
+
+Add Validation
+--------------
+
+ User.setHashedPassword('sha256', validatePassword);
+
+ function validatePassword(value) {
+ return value && value.length >= 4;
+ }
1  index.js
@@ -0,0 +1 @@
+module.exports = require('./lib/mongoose-hashed-password');
46 lib/mongoose-hashed-password.js
@@ -0,0 +1,46 @@
+/*!
+ * mongoose-hashed-password
+ * Copyright(c) 2012 Keisuke Tada <tdkskdt@gmail.com>
+ * MIT Licensed
+ */
+
+var mongoose = require('mongoose'),
+ crypto = require('crypto');
+
+var Schema = mongoose.Schema;
+
+/**
+ * Add a new function to the schema prototype
+ * to set a hashed password instead of a raw password
+ */
+Schema.prototype.setHashedPassword = function (algorithm, validate) {
+ this.add({
+ hashed_password: String
+ , salt: String
+ });
+
+ this.virtual('password').set(function (pw) {
+ this._password = pw;
+ this.salt = this.createSalt();
+ this.hashed_password = this.encryptPassword(pw);
+ }).get(function () {
+ return this._password;
+ });
+
+ this.methods.authenticate = function (plain) {
+ return this.encryptPassword(plain) === this.hashed_password;
+ };
+
+ this.methods.createSalt = function () {
+ return Math.round(new Date().valueOf() * Math.random()) + '';
+ };
+
+ this.methods.encryptPassword = function (str) {
+ return crypto.createHmac(algorithm, this.salt).update(str).digest('hex');
+ };
+
+ this.pre('save', function (next) {
+ if (validate && !validate(this.password)) return next(new Error('Invalid password'));
+ next();
+ });
+};
15 package.json
@@ -0,0 +1,15 @@
+{
+ "name": "mongoose-hashed-password",
+ "description": "hashed password setter to mongoose schema",
+ "version": "0.0.1",
+ "author": {
+ "name": "Keisuke Tada",
+ "email": "tdkskdt@gmail.com"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/tdksk/mongoose-hashed-password"
+ },
+ "dependencies": {},
+ "devDependencies": {}
+}
Please sign in to comment.
Something went wrong with that request. Please try again.