Skip to content

Instantly share code, notes, and snippets.

@mhupman
Last active December 15, 2015 23:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mhupman/5337835 to your computer and use it in GitHub Desktop.
Save mhupman/5337835 to your computer and use it in GitHub Desktop.
User = describe 'User', ->
property 'username', String
property 'password_hash', String
property 'password_salt', String
set 'restPath', pathTo.users
module.exports = (compound, User) ->
crypto = require 'crypto'
User.prototype.toString = ->
@username
User.registerProperty 'password'
User.setter.password = (clearPass) ->
@_password = clearPass # Required for validation
@password_salt = @makeSalt()
@password_hash = @encryptPassword(clearPass)
User.prototype.authenticate = (plainText) ->
@encryptPassword(plainText) == @password_hash
User.prototype.makeSalt = (date) ->
Math.round(((date || new Date()).valueOf() * Math.random())) + ''
User.prototype.encryptPassword = (pass)->
crypto.createHmac('sha512', @password_salt).update(pass).digest('hex')
User.beforeValidate = (done, data) ->
if (data.password)
@password = data.password
data['password_hash'] = @password_hash
data['password_salt'] = @password_salt
done()
User.beforeSave = (done, data) ->
# Ensure password doesn't make it through to the db during udpateAttributes.
# This may only be an issue with the MongoDB adapter, haven't tested others.
delete data.password
done()
User.validatesPresenceOf('username', 'password')
User.validatesLengthOf('password', {min: 6, message: {min: 'Password must be at least 6 characters.'}})
User.validatesUniquenessOf('username', {message: 'username is not unique'})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment