upd
This commit is contained in:
@@ -0,0 +1,35 @@
|
||||
import bcrypt from "bcrypt";
|
||||
import { Router } from "express";
|
||||
import User from "../models/User.js";
|
||||
import Token from "../models/Token.js";
|
||||
|
||||
const router = Router();
|
||||
|
||||
router.post("/", async (req, res) => {
|
||||
const { oldPassword, newPassword } = req.body;
|
||||
|
||||
try {
|
||||
const user = res.locals.user;
|
||||
const accessToken = res.locals.accessToken;
|
||||
|
||||
if (!bcrypt.compareSync(oldPassword, user.password)) {
|
||||
return res.json({ error: "Old password is wrong" });
|
||||
}
|
||||
|
||||
const newPasswordHash = bcrypt.hashSync(newPassword, 12);
|
||||
|
||||
await User.findByIdAndUpdate(user._id, { password: newPasswordHash });
|
||||
await Token.deleteMany({
|
||||
userId: user._id,
|
||||
accessToken: { $ne: accessToken },
|
||||
});
|
||||
|
||||
return res.json({ ok: 1 });
|
||||
} catch (error) {
|
||||
return res.json({ error: (error as Error).message });
|
||||
}
|
||||
});
|
||||
|
||||
const changePasswordRoute = router;
|
||||
|
||||
export default changePasswordRoute;
|
||||
@@ -285,6 +285,17 @@ router.get(
|
||||
}
|
||||
);
|
||||
|
||||
router.get("/:companyId/users", async (req, res) => {
|
||||
try {
|
||||
const companyId = req.params.companyId;
|
||||
const users = await User.find({ companyId });
|
||||
|
||||
return res.json(users);
|
||||
} catch (error) {
|
||||
return res.json({ error: (error as Error).message });
|
||||
}
|
||||
});
|
||||
|
||||
const companiesRouter = router;
|
||||
|
||||
export default companiesRouter;
|
||||
|
||||
@@ -11,17 +11,17 @@ router.post("/", async (req, res) => {
|
||||
const { username, password } = req.body;
|
||||
|
||||
if (!username || !password) {
|
||||
return res.json({ error: 1 });
|
||||
return res.json({ error: "Неверный логин или пароль" });
|
||||
}
|
||||
|
||||
const user = await User.findOne({ username }).lean();
|
||||
|
||||
if (!user) {
|
||||
return res.json({ error: 2 });
|
||||
return res.json({ error: "Неверный логин или пароль" });
|
||||
}
|
||||
|
||||
if (!bcrypt.compareSync(password, user.password!)) {
|
||||
return res.json({ error: 3 });
|
||||
return res.json({ error: "Неверный логин или пароль" });
|
||||
}
|
||||
|
||||
const accessToken = await new SignJWT({ username })
|
||||
@@ -36,12 +36,14 @@ router.post("/", async (req, res) => {
|
||||
|
||||
await Token.create({ userId: user._id, accessToken, refreshToken });
|
||||
|
||||
const userWithoutPassword = { ...user, password: undefined };
|
||||
|
||||
res
|
||||
.cookie("refreshToken", refreshToken, {
|
||||
httpOnly: true,
|
||||
expires: new Date(decodeJwt(refreshToken).exp! * 1000),
|
||||
})
|
||||
.json({ accessToken, refreshToken, ...user });
|
||||
.json({ accessToken, refreshToken, ...userWithoutPassword });
|
||||
});
|
||||
|
||||
const loginRoute = router;
|
||||
|
||||
Reference in New Issue
Block a user