Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const http = require('http')
- const sqlite3 = require('sqlite3')
- const hostname = '127.0.0.1'
- const port = 3000;
- var db = null;
- const open = (filename) => {
- db = new sqlite3.Database(filename);
- }
- const close = () => {
- db.run("pragma analysis_limit = 100");
- db.run("pragma optimize");
- db.close();
- }
- const ensure = (filename) => {
- if (db == null) { open(filename); }
- }
- const create = (filename) => {
- ensure(filename);
- db.run("pragma trusted_schema = false")
- db.run("pragma journal_mode = WAL")
- // can't figure out how to config defensive from node
- db.serialize(() => {
- db.run("drop table if exists users")
- .run(`create table users(username text primary key not null,
- plainpass text not null)`)
- })
- }
- const uuid = (cb) => {
- db.get("select lower(hex(randomblob(16))) as uuid", cb)
- }
- const create_user = (username, plainpass) => {
- db.run(`insert into users values('${username}', '${plainpass}')`)
- }
- const valid_plainpass = (username, checkpass, valid, invalid) => {
- db.get(`select plainpass from users where username='${username}'`, (err, row) => {
- if (row && row.plainpass === checkpass)
- valid()
- else
- invalid()
- })
- }
- const web_create_user = (req, res) => {
- uuid((err, row) => {
- const username = row.uuid
- uuid((err, row) => {
- const plainpass = row.uuid
- create_user(username, plainpass)
- res.writeHead(200, { 'Content-Type': 'text/plain' })
- res.end(`Created user ${username} with pass ${plainpass}`)
- })
- })
- }
- const web_check_password = (req, res) => {
- uuid((err, row) => {
- const username = row.uuid
- uuid((err, row) => {
- const plainpass = row.uuid
- const valid = () => {
- res.writeHead(200, { 'Content-Type': 'text/plain' })
- res.end(`Checked user ${username} with pass ${plainpass}: valid`)
- }
- const invalid = () => {
- res.writeHead(200, { 'Content-Type': 'text/plain' })
- res.end(`Checked user ${username} with pass ${plainpass}: invalid`)
- }
- valid_plainpass(username, plainpass, valid, invalid)
- })
- })
- }
- const web_default = (req, res) => {
- res.writeHead(200, { 'Content-Type': 'text/plain' })
- res.end(`Try paths /create or /check`)
- }
- const dbfile = "test-js-userdb.sqlite"
- create(dbfile);
- const server = http.createServer((req, res) => {
- switch (req.url) {
- case "/create": return web_create_user(req, res)
- case "/check": return web_check_password(req, res)
- default: return web_default(req, res)
- }
- })
- server.listen(port, hostname, () => {
- console.log(`listening at http://${hostname}:${port}`)
- })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement