· 4 years ago · Jan 16, 2021, 07:44 PM
1const http = require('http')
2const sqlite3 = require('sqlite3')
3const hostname = '127.0.0.1'
4const port = 3000;
5
6var db = null;
7
8const open = (filename) => {
9 db = new sqlite3.Database(filename);
10}
11
12const close = () => {
13 db.run("pragma analysis_limit = 100");
14 db.run("pragma optimize");
15 db.close();
16}
17
18const ensure = (filename) => {
19 if (db == null) { open(filename); }
20}
21
22const create = (filename) => {
23 ensure(filename);
24 db.run("pragma trusted_schema = false")
25 db.run("pragma journal_mode = WAL")
26 // can't figure out how to config defensive from node
27
28 db.serialize(() => {
29 db.run("drop table if exists users")
30 .run(`create table users(username text primary key not null,
31 plainpass text not null)`)
32 })
33}
34
35const uuid = (cb) => {
36 db.get("select lower(hex(randomblob(16))) as uuid", cb)
37}
38
39const create_user = (username, plainpass) => {
40 db.run(`insert into users values('${username}', '${plainpass}')`)
41}
42
43const valid_plainpass = (username, checkpass, valid, invalid) => {
44 db.get(`select plainpass from users where username='${username}'`, (err, row) => {
45 if (row && row.plainpass === checkpass)
46 valid()
47 else
48 invalid()
49 })
50}
51
52const web_create_user = (req, res) => {
53 uuid((err, row) => {
54 const username = row.uuid
55 uuid((err, row) => {
56 const plainpass = row.uuid
57 create_user(username, plainpass)
58 res.writeHead(200, { 'Content-Type': 'text/plain' })
59 res.end(`Created user ${username} with pass ${plainpass}`)
60 })
61 })
62}
63
64const web_check_password = (req, res) => {
65 uuid((err, row) => {
66 const username = row.uuid
67 uuid((err, row) => {
68 const plainpass = row.uuid
69 const valid = () => {
70 res.writeHead(200, { 'Content-Type': 'text/plain' })
71 res.end(`Checked user ${username} with pass ${plainpass}: valid`)
72 }
73 const invalid = () => {
74 res.writeHead(200, { 'Content-Type': 'text/plain' })
75 res.end(`Checked user ${username} with pass ${plainpass}: invalid`)
76 }
77
78 valid_plainpass(username, plainpass, valid, invalid)
79 })
80 })
81}
82
83const web_default = (req, res) => {
84 res.writeHead(200, { 'Content-Type': 'text/plain' })
85 res.end(`Try paths /create or /check`)
86
87}
88
89const dbfile = "test-js-userdb.sqlite"
90create(dbfile);
91
92const server = http.createServer((req, res) => {
93 switch (req.url) {
94 case "/create": return web_create_user(req, res)
95 case "/check": return web_check_password(req, res)
96 default: return web_default(req, res)
97
98 }
99})
100
101
102server.listen(port, hostname, () => {
103 console.log(`listening at http://${hostname}:${port}`)
104})
105
106