Created
April 30, 2011 04:31
-
-
Save mrjjwright/949413 to your computer and use it in GitHub Desktop.
My approach to node security
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Security code for a user | |
| uuid = require "node-uuid" | |
| crypto = require "crypto" | |
| util = require("util") | |
| systemSalt = "49caa18ae0d91e9ad610eba6bf6328172ae026a497ef6e79dcb0b7b1eb1ca534a047405eb8f0f05b2e513d548a3d97a0d4a2634593ac98d5e1db64212837b254" | |
| # Default fingerprint function | |
| fingerprint = (user) -> | |
| return user.email | |
| # Default hash function | |
| hash = (user, base) -> | |
| return crypto.createHmac('sha256', systemSalt) | |
| .update(base + fingerprint(user)) | |
| .digest('base64') | |
| .replace(/=*$/, '') | |
| # Generate an accessToken for a user | |
| exports.generateAccessToken = generateAccessToken = (user) -> | |
| base = uuid() | |
| expirationTimestamp = new Date().getTime() | |
| user.accessToken = base + '.' + expirationTimestamp + "." + hash(user, base) | |
| hashPassword = (password, uniqueSalt) -> | |
| # hash the user's password | |
| passwordHashed = crypto.createHash("sha256") | |
| .update(password) | |
| .digest('base64') | |
| # hash systemSalt + user.passwordSalt + the hashed password | |
| return crypto.createHash("sha256") | |
| .update(systemSalt + ";" + uniqueSalt + ";" + passwordHashed) | |
| .digest('base64') | |
| # We store the user's hashed password in the database | |
| # but with a file stored system wide salt and a unique per login salt so that brute force | |
| # attacks are more unlikely. | |
| exports.securePassword = securePassword = (password, user) -> | |
| # First generate a new unique salt and hash it | |
| user.passwordSalt = crypto.createHash("sha256") | |
| .update(uuid()) | |
| .digest('base64') | |
| user.passwordHash = hashPassword(password, user.passwordSalt) | |
| return user | |
| exports.checkPassword = checkPassword = (password, user) -> | |
| return hashPassword(password, user.passwordSalt) is user.passwordHash | |
| exports.secure = secure = (password, user) -> | |
| securePassword(password, user) | |
| generateAccessToken(user) | |
| return user |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment