import * as express from "express"; import * as bodyparser from "body-parser"; import { isAuthenticated, performLogin } from "./security/auth"; import UserRouter from "./api/user"; import ClassRouter from "./api/class"; import LevelRouter from "./api/level"; const baseRouter = express.Router(); const authRouter = express.Router(); authRouter.use(bodyparser.json()); authRouter.use(async (req, res, next) => { const token = req.get("Token"); if (token) { // Check if were authenticated const auth = await isAuthenticated(token); if (auth) next(); else res.send({ error: "401", data: {}, }); } else { res.send({ error: "401", data: {}, }); } }); const app = express(); app.use(bodyparser.json()); app.use((req, res, next) => { // TODO: Change this to our domain res.append("Access-Control-Allow-Origin", "*"); res.append("Access-Control-Allow-Headers", "Content-Type,Token"); next(); }); app.use("/api/level", LevelRouter); app.use("/api/class", ClassRouter); app.use("/api/user", UserRouter); app.get("/api/health", (req, res) => { res.send({ error: "0", data: { msg: "lol", }, }); }); app.post("/api/login", async (req, res) => { const { body } = req; console.log("Stub: /login"); // Check if all arguments were sent if (!body || !("username" in body) || !("password" in body)) { res.send({ error: "400", data: { msg: "Username or password not specified", }, }); return; } // Try to log the user in const userData = await performLogin(body.username, body.password) .catch((err) => { console.log("Could not resolve login promise!", err); // If anything was wrong, just tell the client res.send({ error: "1", data: { msg: "Username or password is wrong", }, }); }); res.send({ error: "0", data: userData, }); }); app.listen(8080, () => { console.log("Starting on port 8080"); });