const express = require('express'); const app = express.Router(); const sqlite = require('better-sqlite3'); const db = new sqlite('the_big_db.db', { verbose: console.log }); const argon2 = require('argon2'); const { loginRequired } = require('../authStuff.js'); // auth stuff app.post('/register', async (req, res) => { const {name, password, nonce} = req.body; const oldUser = db.prepare('select name from users where name=?').get(name); if (oldUser) return res.status(500).json({"error": "user name already in use"}); // check if the nonce password is correctt if (nonce != "a softer birdsong") return res.status(500).json({"error": "wrong nonce"}); try { // i'm told argon2 is the good one nowatimes const hash = await argon2.hash(password); const inserted = db.prepare('insert into users (name, password) values (?, ?)').run(name, hash); res.status(200).json(inserted); } catch (error) { res.status(500).json({"error": error}); } }); app.post('/login', async (req, res) => { if (req.session.name) { return res.status(200).json({message: "already logged in", name: req.session.name}); } const {name, password} = req.body; // fetch username and passswords from the db const storedUser = db.prepare('select * from users where name = ?').get(name); if (!storedUser) { return res.status(401).json({"error": "password/username combo not found in database"}); } //check if the passss hashes mattch and log in if (!(await argon2.verify(storedUser.password, password))) { return res.status(401).json({"error": "password/username combo not found in database"}); } // set the session cookie and rreturn 200! req.session.name = name; req.session.userId = storedUser.id; console.log('setting req.session.name! : ', req.session); return res.status(200).json({message: "successfully logged in!", id: storedUser.id, name: name}); }); app.post('/logout', (req, res) => { req.session.destroy(); res.status(200).json({message: "successfully logged out"}); }); app.get('/user', loginRequired, (req, res) => { res.status(200).json({ "id": req.session.userId, "name": req.session.name, "favoriteColor": "red", "leastFavoriteColor": "also red" }); }); module.exports = app;