Skip to content

Instantly share code, notes, and snippets.

@OneCent01
Last active October 7, 2019 23:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save OneCent01/fa52829c9770472d16a5af20b6f75a16 to your computer and use it in GitHub Desktop.
Save OneCent01/fa52829c9770472d16a5af20b6f75a16 to your computer and use it in GitHub Desktop.
Secure NodeJS server with add and auth users; salted and hashed passes, token authentication, and apply secure response headers
// This should be an external database in real development. This is just for simplified demonstration.
const memoryDB = {
users: {},
usersCount: 0
}
const express = require('express')
const obsidian = require('obsidian-js')
const bodyParser = require('body-parser')
const app = express()
app.use(obsidian.obsidianWare({unrestrictedPaths: ['/', '/add-user', '/auth-user']}))
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
app.get('/', (req, res) => res.send('test working'))
app.post('/add-user', async (req, res) => {
const {email, password} = req.body
const validInputs = (email && email.length && password && password.length)
if(!validInputs) {
return res.send(JSON.stringify({succes: false, error: 'EMAIL AND PASSWORD REQUIRED'}))
} else if(memoryDB[email]) {
return res.send(JSON.stringify({success: false, error: 'EMAIL ALREADY EXISTS IN DB'}))
}
const salt = await obsidian.secureSalt(8)
const saltedPass = `${salt}${password}`
memoryDB.users[email] = {
id: memoryDB.usersCount++,
hash: await obsidian.hash(saltedPass),
salt: salt
}
res.send(JSON.stringify({success: true}))
})
app.post('/auth-user', async (req, res) => {
const {email, password} = req.body
const validInputs = (email && email.length && password && password.length)
if(!validInputs) {
return res.send(JSON.stringify({succes: false, error: 'EMAIL AND PASSWORD REQUIRED'}))
} else if(!memoryDB.users[email]) {
return res.send(JSON.stringify({success: false, error: 'EMAIL DOES NOT EXISTS IN DB'}))
}
const user = memoryDB.users[email]
const isValidHash = await obsidian.verifyHash(`${user.salt}${password}`, user.hash)
if(!isValidHash) {
return res.send(JSON.stringify({success: false, error: 'INVALID CREDENTIALS'}))
}
res.send(JSON.stringify({success: true, token: obsidian.issueToken({id: user.id})}))
})
app.post('/auth-path', (req, res) => res.send(JSON.stringify({success: true, message: "My God, you've dont it!"})))
app.listen(3000, () => console.log('listening on port 3000...'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment