Archived
1
0
Fork 0
This repository has been archived on 2024-02-17. You can view files and clone it, but cannot push or open issues or pull requests.
SOD/routes/profile.js

64 lines
2.5 KiB
JavaScript
Raw Normal View History

2020-08-17 17:58:55 +02:00
let express = require("express");
let router = express.Router();
let sessionCheck = require("../middlewares/sessionCheck");
let models = require("../models");
2020-08-20 12:14:38 +02:00
let error = require("./utils/error");
2020-08-17 17:58:55 +02:00
router.get("/", sessionCheck(0), async (req, res) => {
res.render("profile", {
2020-08-17 19:13:00 +02:00
title: "SOD - Profile",
2020-08-17 17:58:55 +02:00
user: req.session.user,
departments: await models.Department.findAll(),
2020-08-18 17:54:00 +02:00
orders: await models.Order.findAll({
2020-08-17 17:58:55 +02:00
where: {UserUsername: req.session.user.username},
include: models.Sandwich,
order: ["date"]
})
});
}).post("/", sessionCheck(0), async (req, res) => {
let user = await models.User.findByPk(req.session.user.username);
/*if (req.body.username && req.body.username !== user.username)
if (await models.User.findByPk(req.body.username))
2020-08-20 12:14:38 +02:00
return error(req, res, "Invalid profile update !", 400, "Username already taken");
2020-08-17 17:58:55 +02:00
else
user.username = req.body.username;*/
if (req.body.email && req.body.email !== user.email)
if (await models.User.findOne({where: {email: req.body.email}}))
2020-08-20 12:14:38 +02:00
return error(req, res, "Invalid profile update !", 400, "Email already used");
2020-08-17 17:58:55 +02:00
else
user.email = req.body.email;
if (req.body.firstName && req.body.lastName &&
(req.body.firstName !== user.firstName || req.body.lastName !== user.lastName))
if (await models.User.findOne({where: {firstName: req.body.firstName, lastName: req.body.lastName}}))
2020-08-20 12:14:38 +02:00
return error(req, res, "Invalid profile update !", 400, "First & last name already register");
2020-08-17 17:58:55 +02:00
else {
user.firstName = req.body.firstName;
user.lastName = req.body.lastName;
2020-08-18 17:54:00 +02:00
for (let c of await models.Order.findAll({where: {
2020-08-17 17:58:55 +02:00
firstName: req.session.user.firstName,
lastName: req.session.user.lastName}})) {
c.firstName = user.firstName;
c.lastName = user.lastName;
await c.save()
}
}
if (req.body.department && req.body.department !== user.DepartmentName)
if (!await models.Department.findByPk(req.body.department))
2020-08-20 12:14:38 +02:00
return error(req, res, "Invalid profile update !", 400, "Invalid department");
2020-08-17 17:58:55 +02:00
else
user.DepartmentName = req.body.department;
if (req.body.password && !user.checkPassword(req.body.password))
user.passwordHash = req.body.password;
await user.save();
req.session.user = user;
res.redirect("/profile");
});
module.exports = router;