qwik-account-manager/routes/auth.js

85 lines
2.4 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 = {}
AUTH.post('/register', (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 (glauth.prepare(`SELECT * FROM users WHERE name = ?`).get(username))
return(res.send("User already exists"))
bcrypt.hash(password, 10).then(
hash => {
glauth.prepare(`
INSERT INTO users(
name, primarygroup, passbcrypt
) VALUES(?, 0, ?)
`).run(username, hash)
res.send("Account registered!")
}
)
})
AUTH.post('/login', (req, res) => {
const { password, username } = req.body
// Was input sent?
if (!username || !password )
return(res.send(`Not entered:${username ? '' : ' username,'}${password ? '' : ' password'}`))
const user = glauth.prepare(`SELECT * FROM users WHERE name = ?`).get(username)
if (!user)
return(res.send("User doesn't exist!"))
bcrypt.compare(password, user.passbcrypt).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