From 4278751837f794174f914b711d17c4d845f22a5e Mon Sep 17 00:00:00 2001 From: Alexander Polynomdivision Date: Sun, 7 Oct 2018 15:41:08 +0200 Subject: [PATCH] feat: Add /api/register endpoint --- backend/src/main.ts | 92 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 91 insertions(+), 1 deletion(-) diff --git a/backend/src/main.ts b/backend/src/main.ts index 0293cf1..288d34c 100644 --- a/backend/src/main.ts +++ b/backend/src/main.ts @@ -1,4 +1,6 @@ -import { env } from "process"; +import { env, exit } from "process"; +// import * as fs from "fs"; +import { randomBytes, pbkdf2Sync } from "crypto"; import * as assert from "assert"; import * as express from "express"; @@ -6,6 +8,9 @@ import * as cors from "cors"; import * as bodyparser from "body-parser"; +//@ts-ignore +//import * as Filter from "bad-words"; + import { isAuthenticated, performLogin } from "./security/auth"; import { LRequest } from "./types/express"; @@ -23,6 +28,12 @@ const user = encodeURIComponent("backend"); const password = encodeURIComponent(env["LATEINICUS_USER_PW"]); (async function() { + // Load the profanity list + // const list = JSON.parse(fs.readFileSync("/etc/profanity", { encoding: "utf-8" })); + // const profanityFilter = new Filter({ + // list, + // }); + // Database Name const dbName = 'lateinicus'; // Connection URL @@ -80,6 +91,85 @@ const password = encodeURIComponent(env["LATEINICUS_USER_PW"]); }, }); }); + app.post("/api/register", async (req, res) => { + // Check if any data was sent + if (!req.body) { + res.send({ + error: "403", + data: { + msg: `No data sent`, + }, + }); + return; + } + + // Check if we have all we need + const params = ["username", "password", "classId"]; + for (let param of params) { + if (!(param in req.body)) { + res.send({ + error: "403", + data: { + msg: `${param} not specified!`, + }, + }); + return; + } + } + + const { username, password, classId } = req.body; + + // TODO: Check if the username is profane + // if (profanityFilter.isProfane(username)) { + // res.send({ + // error: "451", + // data: { + // msg: "Profane username", + // }, + // }); + // return; + // } + + // Check if the user already exists + const checkUser = await db.collection("users").findOne({ + username, + }); + if (checkUser) { + res.send({ + error: "403", + data: { + msg: "User already exists", + }, + }); + return; + } + + const salt = randomBytes(30).toString("hex"); + const hash = pbkdf2Sync(password, salt, 50000, 512, "sha512").toString("hex"); + const user = { + username, + salt, + hash, + classId, + score: 0, + showWelcome: true, + + lastReview: { + correct: 0, + wrong: 0, + }, + + lastLevel: 0, + levels: [] as number[], + vocabMetadata: {}, + }; + await db.collection("users").insertOne(user); + + res.send({ + error: "200", + data: {}, + }); + }); app.get("/api/health", (req, res) => { res.send({ error: "0",