the-forest/server/routes/users.js

70 lines
2.2 KiB
JavaScript
Raw Normal View History

const express = require('express');
const app = express.Router();
const sqlite = require('better-sqlite3');
2024-10-05 12:01:19 -04:00
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
2024-10-05 12:01:19 -04:00
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;
2024-10-05 12:01:19 -04:00
req.session.userId = storedUser.id;
console.log('setting req.session.name! : ', req.session);
2024-10-05 12:01:19 -04:00
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({
2024-10-05 12:01:19 -04:00
"id": req.session.userId,
"name": req.session.name,
"favoriteColor": "red",
"leastFavoriteColor": "also red"
});
});
module.exports = app;