qwik-account-manager/routes/auth.js

85 lines
2.4 KiB
JavaScript
Raw Normal View History

2022-01-22 21:32:14 +01:00
import bcrypt from 'bcrypt'
2022-01-15 19:27:18 +01:00
import crypto from 'crypto'
import { Router } from 'express'
2022-01-22 21:32:14 +01:00
import { glauth } from '../libs/database.js'
2022-01-15 19:27:18 +01:00
import execawait from '../libs/execawait.js'
const AUTH = Router()
let valid = {}
AUTH.post('/register', (req, res) => {
2022-01-22 21:32:14 +01:00
const { captcha, password, username } = req.body
2022-01-15 19:27:18 +01:00
2022-01-22 21:32:14 +01:00
// Was input sent?
if (!username || !password || !captcha)
return(res.send(`Not entered:${username ? '' : ' username,'}${password ? '' : ' password,'}${captcha ? '' : ' captcha'}`))
2022-01-15 19:27:18 +01:00
// is captcha valid
2022-01-22 21:32:14 +01:00
if (!valid[captcha])
2022-01-15 19:27:18 +01:00
return(res.send("Invalid captcha!"))
2022-01-22 21:32:14 +01:00
const captchaAge = Math.abs((valid[captcha].getTime() - new Date().getTime())/1000)
2022-01-15 19:27:18 +01:00
2022-01-22 21:32:14 +01:00
if (captchaAge > 600)
2022-01-15 19:27:18 +01:00
return(res.send("Invalid captcha!"))
// expire the captcha
2022-01-22 21:32:14 +01:00
delete valid[captcha]
2022-01-15 19:27:18 +01:00
2022-01-22 21:32:14 +01:00
// 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))
2022-01-15 19:27:18 +01:00
return(res.send("User already exists"))
2022-01-22 21:32:14 +01:00
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!"))
2022-01-15 19:27:18 +01:00
2022-01-22 21:32:14 +01:00
bcrypt.compare(password, user.passbcrypt).then(
match => {
if (!match)
return res.send("Password's is incorrect!")
2022-01-15 19:27:18 +01:00
2022-01-22 21:32:14 +01:00
return res.send("Welcome " + user.name + "!")
}
)
2022-01-15 19:27:18 +01:00
})
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
2022-01-22 21:32:14 +01:00
res.contentType('image/png')
.sendFile('captcha.png', { root: './' })
2022-01-15 19:27:18 +01:00
})
export default AUTH