102 lines
2.9 KiB
JavaScript
102 lines
2.9 KiB
JavaScript
import bcrypt from 'bcrypt'
|
|
import crypto from 'crypto'
|
|
import { Router } from 'express'
|
|
import { glauth } from '../libs/database.js'
|
|
import execawait from '../libs/execawait.js'
|
|
|
|
const AUTH = Router()
|
|
let valid = {}
|
|
|
|
/**
|
|
* ...
|
|
* @param {string} hash The hash to be converted to hex.
|
|
* @returns {string} hex of hash
|
|
*/
|
|
function hash2hex(hash) {
|
|
return hash
|
|
.split('')
|
|
.map(e => e
|
|
.charCodeAt(0)
|
|
.toString(16)
|
|
)
|
|
.join('')
|
|
}
|
|
|
|
AUTH.post('/register', async (req, res) => {
|
|
const { captcha, password, username } = req.body
|
|
|
|
// Was input sent?
|
|
if (!username || !password || !captcha)
|
|
return(res.send(`Not entered:${username ? '' : ' username,'}${password ? '' : ' password,'}${captcha ? '' : ' captcha'}`))
|
|
|
|
// is captcha valid
|
|
if (!valid[captcha])
|
|
return(res.send("Invalid captcha!"))
|
|
|
|
const captchaAge = Math.abs((valid[captcha].getTime() - new Date().getTime())/1000)
|
|
|
|
if (captchaAge > 600)
|
|
return(res.send("Invalid captcha!"))
|
|
|
|
// expire the captcha
|
|
delete valid[captcha]
|
|
|
|
// does the username match the requirements
|
|
if (!(/^(?=[a-zA-Z0-9]{2,20}$).*$/.test(username)))
|
|
return(res.send("Username does not match the requirements"))
|
|
|
|
if ((await glauth.query("SELECT * FROM users WHERE name = $1::text", [ username ])).rowCount)
|
|
return(res.send("User already exists"))
|
|
|
|
bcrypt.hash(password, 10).then(
|
|
hash => {
|
|
const hexHash = hash2hex(hash)
|
|
glauth.query(
|
|
"INSERT INTO users(name, primarygroup, passbcrypt, qam_pass) VALUES($1::text, 0, $2::text, $3::text)",
|
|
[ username, hexHash, hash ]
|
|
).then(
|
|
() => res.send("Account registered!")
|
|
).catch(
|
|
err => res.json({ _: "Sorry an error occured!", err })
|
|
)
|
|
|
|
}
|
|
)
|
|
})
|
|
|
|
AUTH.post('/login', async (req, res) => {
|
|
const { password, username } = req.body
|
|
|
|
// Was input sent?
|
|
if (!username || !password )
|
|
return(res.send(`Not entered:${username ? '' : ' username,'}${password ? '' : ' password'}`))
|
|
|
|
const user = (await glauth.query("SELECT * FROM users WHERE name = $1::text", [ username ])).rows[0]
|
|
|
|
if (!user)
|
|
return(res.send("User doesn't exist!"))
|
|
|
|
bcrypt.compare(password, user.qam_pass).then(
|
|
match => {
|
|
if (!match)
|
|
return res.send("Password's is incorrect!")
|
|
|
|
return res.send("Welcome " + user.name + "!")
|
|
}
|
|
)
|
|
})
|
|
|
|
AUTH.get('/captcha', async (req, res) => {
|
|
const captcha = crypto.randomBytes(3).toString('hex')
|
|
await execawait(`./captcha.sh ${captcha} > captcha.png`)
|
|
|
|
// Make it valid for 10 minutes
|
|
valid[captcha] = new Date()
|
|
|
|
// Send the captcha image
|
|
res.contentType('image/png')
|
|
.sendFile('captcha.png', { root: './' })
|
|
})
|
|
|
|
|
|
export default AUTH |