Login.js 1.47 KB
const axios = require("axios");
const express = require("express");
const router = express.Router();

const { login } = require("../libs/E_Campus.js");
const parseICal = require("../libs/ICal.js");
const { jcalToSQL } = require("../libs/MySQL.js");
require("dotenv").config();

// (id, pw) => failed | error | {peed, subjects, name, ID}
router.post("/", async (req, res) => {
  console.log(`listened /login ${req.body.id} ${req.body.pw}`);
  const result = await login(req.body.id, req.body.pw);
  if (result && result !== "error") {
    try {
      const { peed, subjects } = result;

      const resUser = await axios.post(
        `http://${process.env.SERVER_IP}:3001/db/users`,
        {
          loginID: req.body.id,
          loginPW: req.body.pw,
          ical: peed,
        }
      );
      const userID = resUser.data.ID;
      const { data: subList } = await axios.post(
        `http://${process.env.SERVER_IP}:3001/db/subjects/s`,
        {
          list: subjects,
        }
      );
      await axios.post(
        `http://${process.env.SERVER_IP}:3001/db/user-subject/s`,
        {
          userID,
          subList,
        }
      );
      const { data: ical } = await axios({
        url: peed,
        method: "GET",
        responseType: "blob",
      });
      await jcalToSQL(parseICal(ical), userID);
      res.send({ userID });
    } catch (e) {
      console.log(e);
      res.send("error");
    }
  } else res.send(result ? "failed" : "error");
});

module.exports = router;