{"size": 1325, "ext": "js", "max_stars_repo_path": "routes/user/update-user.js", "max_stars_repo_name": "Makuwro/makuwiki-server", "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "routes/user/update-user.js", "max_issues_repo_name": "Makuwro/makuwiki-server", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "routes/user/update-user.js", "max_forks_repo_name": "Makuwro/makuwiki-server", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": null, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 22.8448275862, "max_line_length": 136, "alphanum_fraction": 0.5811320755}
const multer = require("multer");

const acceptedFileRegex = /\.(png|jpg|gif)$/gm;
const userIds = {};
const uploadAvatar = multer({ 
  storage: multer.diskStorage({
    destination: "avatars/",
    filename: (req, file, cb) => cb(null, "User_" + userIds[req.header("sessionToken")] + file.originalname.match(acceptedFileRegex)[0])
  }),
  fileFilter: (req, file, cb) => cb(null, file.originalname.match(acceptedFileRegex) !== null)
}).single("avatar");

module.exports = async app => {

  const database = await require("../../database");
  
  app.put("/api/user", async (req, res) => {
    
    const token = req.header("token");
    
    // Make sure we got the main stuff
    if (!token) {

      res.status(400).json({error: "Missing token"});
      return;

    }
    
    // Make sure session exists
    const userInfo = token && database.mongoClient.db("Accounts").collection("Users").findOne({token: token});
    if (!userInfo) {

      res.status(400).json({error: "Invalid token"});
      return;

    }
    
    userIds[token] = userInfo.userId;
    uploadAvatar(req, res, err => {
      
      if (err) {

        console.log("[User Updating] Failed to update avatar: " + err);
        res.sendStatus(500);

      } else {

        // Success!
        res.sendStatus(200);

      }
    
    });
    
  });
  
};
